package java_demos.java_basic.connect_mysql;

import java.sql.*;

public class MysqlDemo {
    // 注册驱动
    static final String MysqlDriver = "com.mysql.cj.jdbc.Driver";
    static final String MysqlUrl = "jdbc:mysql://localhost:3306/hongxing?useSSL=false&serverTimezone=UTC";
    static final String username = "root";
    static final String password = "123456";

    public static void main(String[] args) {
        // 连接对象
        Connection conn = null;
        // 语句对象
        Statement stmt = null;
        try {
            // 注册驱动
            Class.forName(MysqlDriver);
            // 连接
            conn = DriverManager.getConnection(MysqlUrl, username, password);

            // 查询
            stmt = conn.createStatement();
            String sql = "SELECT * FROM user";
            ResultSet resultSet = stmt.executeQuery(sql);
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                String address = resultSet.getString("address");
                String email = resultSet.getString("email");
                String phone = resultSet.getString("phone");

                // 输出结果
                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age + ", Gender: " + gender +
                        ", Address: " + address + ", Email: " + email + ", Phone: " + phone);
            }
            resultSet.close();
            stmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found. Include it in your library path ");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
